<?php
namespace Admin\Controller;

use Think\Controller;

class WithdrawalController extends RightController
{
    // 加载初始化内容页,并检索
    public function index()
    {
        //判断分页时搜索条件
        if (I("get.p")) {
            $where = session("QG_SEARCH_WHERE_withdrawal");
            $this->assign("params", session("QG_SEARCH_PARAMS_withdrawal"));
            $where = empty($where) ? "1" : $where;
            $pageSize = session("QG_SEARCH_SIZE_withdrawal");
        } else {
            //清除session存储
            session("QG_SEARCH_WHERE_withdrawal", null);
            session("QG_SEARCH_PARAMS_withdrawal", null);
            session("QG_SEARCH_SIZE_withdrawal", null);
            $pageSize = I("post.pageSize");

            $where = "1";
        }

        // POST数据提交，重新组合检索条件
        if (IS_POST) {
            unset($_GET["p"]);
            $where = $this->searchCondition();
        }
		
		// 分页输入
        if(empty($pageSize)){
            $pageSize = 10;
        }

        // 总条数
        $count = M('withdrawal')
            ->alias("t")
            ->join(" LEFT JOIN admin ua ON ua.id = t.adminId")
            ->join(" LEFT JOIN agen a ON a.id = t.agenId")
            ->where($where)
            ->count();
        $page = new \Admin\Model\Page($count, $pageSize);
        $show = $page->show();

        // 进行分页数据查询
        $list = M('withdrawal')
            ->alias("t")
            ->field("t.*,ua.name as adminname,a.name as agenname,a.account as account")
            ->join(" LEFT JOIN admin ua ON ua.id = t.adminId")
            ->join(" LEFT JOIN agen a ON a.id = t.agenId")
            ->where($where)
            ->order('t.id DESC')
            ->limit($page->firstRow . ',' . $page->listRows)->select();
			
		// 统计
        $sum = M('withdrawal')
            ->alias("t")
            ->field("count(1) as countNum")
            ->where($where)
            ->order('t.id DESC')
            ->find();

        // 渲染查询条件到session
        session("QG_SEARCH_WHERE_withdrawal", $where);
		session("QG_SEARCH_PARAMS_withdrawal", I("post."));
		session("QG_SEARCH_SIZE_withdrawal", $pageSize);
		
		// 输出数据
        $this->assign("params", I("post."));
        $this->assign('list', $list);
        $this->assign('sum', $sum);
		$this->assign('lists', array(
            "page" => getDropdownList("pageSize" , "" ,false),
            "withdrawalStatus" => getDropdownList("withdrawalStatus" , "" )
        ));
        $this->assign('page', $show);
        $this->display();
    }

    // 搜索条件
    public function searchCondition()
    {
        $where = "1";

        // 代理商ID
        if (I('post.agenid')) {
            $where .= " AND t.agenId='" . I("post.agenid") . "'";
        }

        // 创建时间
        if (I('post.createtimeStart') || I('post.createtimeEnd')) {
            // 起始日期
            if(I('post.createtimeStart')){
                $where .= " AND t.createTime>='" . I("post.createtimeStart") . "'";
            }
            // 结束日期
            if(I('post.createtimeEnd')){
                $where .= " AND t.createTime<='" . I("post.createtimeEnd") . " 23:59:59'";
            }
        }

        // 更新时间
        if (I('post.updatetimeStart') || I('post.updatetimeEnd')) {
            // 起始日期
            if(I('post.updatetimeStart')){
                $where .= " AND t.updateTime>='" . I("post.updatetimeStart") . "'";
            }
            // 结束日期
            if(I('post.updatetimeEnd')){
                $where .= " AND t.updateTime<='" . I("post.updatetimeEnd") . " 23:59:59'";
            }
        }

        // 审核管理账户
        if (I('post.adminid')) {
            $where .= " AND t.adminId='" . I("post.adminid") . "'";
        }

        // 支行信息
        if (I('post.branch')) {
            // 精确
            if (I('post.branchCondition') == 1) {
                $where .= " AND t.branch='" . I("post.branch") . "'";
            } else {
                $where .= " AND t.branch LIKE '%" . I("post.branch") . "%'";
            }
        }

        // 名字
        if (I('post.name')) {
            // 精确
            if (I('post.nameCondition') == 1) {
                $where .= " AND t.name='" . I("post.name") . "'";
            } else {
                $where .= " AND t.name LIKE '%" . I("post.name") . "%'";
            }
        }

        // 卡号
        if (I('post.number')) {
            // 精确
            if (I('post.numberCondition') == 1) {
                $where .= " AND t.number='" . I("post.number") . "'";
            } else {
                $where .= " AND t.number LIKE '%" . I("post.number") . "%'";
            }
        }

        // 提现额度
        if (I('post.amountStart') || I('post.amountEnd')) {
            // 开始
            if(I('post.amountStart')){
                $where .= " AND t.amount>='" . I("post.amountStart") . "'";
            }
            // 结束
            if(I('post.amountEnd')){
                $where .= " AND t.amount<='" . I("post.amountEnd") . "'";
            }
        }

        // 状态
        if (I('post.status')) {
            $where .= " AND t.status='" . I("post.status") . "'";
        }

        // 应到金额
        if (I('post.cashStart') || I('post.cashEnd')) {
            // 开始
            if(I('post.cashStart')){
                $where .= " AND t.cash>='" . I("post.cashStart") . "'";
            }
            // 结束
            if(I('post.cashEnd')){
                $where .= " AND t.cash<='" . I("post.cashEnd") . "'";
            }
        }

        // 银行名称
        if (I('post.bankname')) {
            // 精确
            if (I('post.banknameCondition') == 1) {
                $where .= " AND t.bankName='" . I("post.bankname") . "'";
            } else {
                $where .= " AND t.bankName LIKE '%" . I("post.bankname") . "%'";
            }
        }

        return $where;
    }

    // 添加提现
    public function add()
    {
        if (IS_POST) {
            // 数据
            $data = array();

            // 代理商ID
            $data['agenId'] = I('post.agenid');

            // 创建时间
            $data['createTime'] = now();

            // 更新时间
            $data['updateTime'] = now();

            // 审核管理账户
            $data['adminId'] = 0;

            // 支行信息
            $data['branch'] = I('post.branch');

            // 名字
            $data['name'] = I('post.name');

            // 卡号
            $data['number'] = I('post.number');

            // 提现额度
            $data['amount'] = I('post.amount');

            // 状态
            $data['status'] = I('post.status');

            // 应到金额
            $data['cash'] = I('post.cash');

            // 银行名称
            $data['bankName'] = I('post.bankname');

            //创建数据
            $result = M('withdrawal')->add($data);

            if ($result) {
				$this->ajaxSuccess("添加成功！");
            } else {
				$this->ajaxError("添加失败！");
            }
        } else {
            $this->display();
        }
    }

    // 编辑资料
    public function edit()
    {
        if (IS_POST) {
            // ID
            $id = I("post.id");
			
			// 没有ID
			if(empty($id)){
				$this->ajaxError("错误！");
			}

            // 判断用户是否存在
            $dbData = M('withdrawal')
                ->where(array("id", $id))
                ->find();

            //判断用户是否存在
            if (empty($dbData)) {
				$this->ajaxError("数据不存在！");
            }

            // 更新数据
            $data = array();

            // 代理商ID
            $data['agenId'] = I('post.agenid');

            // 创建时间
            $data['createTime'] = I('post.createtime');

            // 更新时间
            $data['updateTime'] = I('post.updatetime');

            // 审核管理账户
            $data['adminId'] = I('post.adminid');

            // 支行信息
            $data['branch'] = I('post.branch');

            // 名字
            $data['name'] = I('post.name');

            // 卡号
            $data['number'] = I('post.number');

            // 提现额度
            $data['amount'] = I('post.amount');

            // 状态
            $data['status'] = I('post.status');

            // 应到金额
            $data['cash'] = I('post.cash');

            // 银行名称
            $data['bankName'] = I('post.bankname');


            // 更新数据
            $result = M('withdrawal')
                ->where(array("id" => $id))
                ->save($data);

            if ($result !== false) {
				$this->ajaxSuccess("更新成功！");
            } else {
				$this->ajaxError("更新失败！");
            }
        } else {
            // ID
            $id = intval(I("get.id"));

            // 判断是否存在
            $data = M('withdrawal')
                ->alias("t")
                ->field("t.*")
                ->where(array("t.id" => $id))
                ->find();

            // 判断是否存在
            if (empty($data)) {
                $this->error("数据不存在");
            }

            $this->assign("data", $data);
            $this->display();
        }
    }

    // 删除
    public function delete()
    {
        if (IS_POST) {
            // ID
            $id = intval(I("post.id"));
			
			// 没有ID
			if(empty($id)){
				$this->ajaxError("错误！");
			}

            //删除数据
            $result = M('withdrawal')->where(array("id" => $id))->delete();

            // 如果删除成功
            if ($result) {
				$this->ajaxSuccess("删除成功！");
            } else {
				$this->ajaxError("删除失败！");
            }
        }
    }

    // 审核数据
    public function confirm(){
        if (IS_POST) {
            // ID
            $id = intval(I("post.id"));

            // 没有ID
            if(empty($id)){
                $this->ajaxError("错误！");
            }

            // 审核数据
            $result = M('withdrawal')->where(array(
                "id" => $id,
                "status" => "1"
            ))->setField(array(
                "status" => "2",
                "adminId" => $this->getAccountId(),
                "updateTime" => now()
            ));

            // 如果删除成功
            if ($result) {
                $this->ajaxSuccess("审核成功！");
            } else {
                $this->ajaxError("审核失败！");
            }
        }
    }

    // 驳回
    public function reject(){
        if (IS_POST) {
            // ID
            $id = intval(I("post.id"));

            // 没有ID
            if(empty($id)){
                $this->ajaxError("错误！");
            }

            $withdrawal = M('withdrawal')->where(array(
                "id" => $id,
                "status" => "1"
            ))->find();
            $agen = M('agen')->where(array(
                "id" => $withdrawal['agenid']
            ))->find();

            // 没有ID
            if(empty($withdrawal)){
                $this->ajaxError("错误！");
            }

            // 开启事务
            M()->startTrans();

            // 驳回数据
            $r[] = M('withdrawal')->where(array(
                "id" => $id,
                "status" => "1"
            ))->setField(array(
                "status" => "3",
                "adminId" => $this->getAccountId(),
                "updateTime" => now()
            ));

            // 更新资金
            $r[] = M("agen")->where(array("id" => $withdrawal['agenid']))->setDec("balance" ,$withdrawal['amount']);

            // 资金记录
            $r[] = agenMoneyLog($agen['id'], $withdrawal['id'], 3, $agen['balance'], $withdrawal['amount'], '提现被驳回:'.$this->getAccount()['name']."-".$this->getAccount()['account']);

            // 如果成功
            if (!in_array(false, $r)) {
                M()->commit();
                $this->ajaxSuccess("驳回成功！");
            } else {
                M()->rollback();
                $this->ajaxError("驳回失败！");
            }
        }
    }

    // 返款
    public function refund(){
        // ID
        $id = intval(I("post.id"));

        // 没有ID
        if(empty($id)){
            $this->ajaxError("错误！");
        }

        $withdrawal = M('withdrawal')->where(array(
            "id" => $id,
            "status" => "2"
        ))->find();
        $agen = M('agen')->where(array(
            "id" => $withdrawal['agenid']
        ))->find();

        // 没有ID
        if(empty($withdrawal)){
            $this->ajaxError("错误！");
        }

        M()->startTrans();

        // 驳回数据
        $r[] = M('withdrawal')->where(array(
            "id" => $id,
            "status" => "2"
        ))->setField(array(
            "status" => "4",
            "adminId" => $this->getAccountId(),
            "updateTime" => now()
        ));

        // 更新资金
        $r[] = M("agen")->where(array("id" => $withdrawal['agenid']))->setDec("balance" ,$withdrawal['amount']);

        // 资金记录
        $r[] = agenMoneyLog($agen['id'], $withdrawal['id'], 3, $agen['balance'], $withdrawal['amount'] , '提现未到账，返款:'.$this->getAccount()['name']."-".$this->getAccount()['account']);

        // 如果成功
        if (!in_array(false, $r)) {
            M()->commit();
            $this->ajaxSuccess("返款成功！");
        } else {
            M()->rollback();
            $this->ajaxError("返款失败！");
        }
    }
}